/**
 * 十三水智能排序
 */

var _ = require('./Underscore');
var CardTool = require('./CardTool');

var GroupFive = require('./CardGroup/GroupFive');
var GroupSameTypeShunZi = require('./CardGroup/GroupSameTypeShunZi');
var GroupASameCardType = require('./CardGroup/GroupASameCardType');
var FindSameCardValueTool = require('./FindTool/FindSameCardValueTool');
var FindSameCardTypeTool = require('./FindTool/FindSameCardTypeTool');
var FindShunZiTool = require('./FindTool/FindShunZiTool');
var FindPairsTool = require('./FindTool/FindPairsTool');

var GroupFourAndOneTool = require('./CardGroup/GroupFourAndOneTool');
var GroupThreeAndAPairs = require('./CardGroup/GroupThreeAndAPairs');
var GroupSameType = require('./CardGroup/GroupSameType');
var GroupShunZi = require('./CardGroup/GroupShunZi');
var GroupFiveThree = require('./CardGroup/GroupFiveThree');
var GroupTwoPairs = require('./CardGroup/GroupTwoPairs');
var GroupFiveAPairs = require('./CardGroup/GroupFiveAPairs');
var CardGroupType = require('./CardGroup/CardGroupType');

var IntelligentTool = module.exports = {};


/***
 * test
 */
IntelligentTool.doTest = function(cardInfoList) {
    /**五同 */
    // result = GroupFive.getMoreResult(cardInfoList);

    /**同花顺 */
    // result = GroupSameTypeShunZi.getMoreResult(cardInfoList);

    /** A同花顺 */
    // result = GroupASameCardType.getMoreResult(cardInfoList);

    /**四带一张 */
    // result = GroupFourAndOneTool.getMoreResult(cardInfoList);

    /**三条一对 */
    // result = GroupThreeAndAPairs.getMoreResult(cardInfoList);

    /**同花 */
    // result = GroupSameType.getMoreResult(cardInfoList);

    /**普通顺子 */
    // result = GroupShunZi.getMoreResult(cardInfoList);

    /**三张牌型 */
    // GroupFiveThree.getMoreResult(cardInfoList);

    /**两对牌型 */
    // result = GroupTwoPairs.getMoreResult(cardInfoList);

    /**只有一对 */
    // GroupFiveAPairs.getMoreResult(cardInfoList);

    /***找顺子 */
    // FindShunZiTool.getMoreResult(cardInfoList, 5);

    /***找同样的牌 */
    // FindSameCardValueTool.getResult(cardInfoList, 3);

    /**找对子*/
    // FindPairsTool.getResult(cardInfoList, 1);
};

/***获取排序结果
 * cardIds:[1,2,3,4,4,5,5,5,5,5]//十三张牌
 * 黑：1-13
 * 红：14-26
 * 梅：27-39
 * 方：40-52
 * 癞子红桃：53-65
 */
IntelligentTool.getResult = function(cardIds, needGroupNumber) {
    if (null == needGroupNumber) {
        needGroupNumber = 3;
    }

    var cardInfoList = this.check(cardIds);

    this.doTest(cardInfoList);

    var result = null;

    result = this.autoFindTwoGroup(cardInfoList, needGroupNumber);

    if (_.size(result) < needGroupNumber) {
        result = this.autoFindOneGroup(cardInfoList, needGroupNumber, result);
    }

    _.each(result, function(_singleGroup, idx) {
        this.log(_singleGroup, idx);
    }.bind(this));



    return result;
};

IntelligentTool.check = function(cardIds) {
    if (null == cardIds) {
        console.error('cardIds 参数为null ');
        return [];
    }
    var len = _.size(cardIds);
    // if (13 != len) {
    //     console.error('cardIds 个数不对 ');
    //     return []
    // }
    var cardInfoList = CardTool.workCards(cardIds);
    // console.error(JSON.stringify(cardInfoList));

    var tmpValues = _.map(cardInfoList, function(cardInfo) {
        return cardInfo.value;
    })

    tmpValues = _.sortBy(tmpValues);

    CardTool.Log(tmpValues, '13张牌值');
    return cardInfoList;
};

/***所有组合情况 */
IntelligentTool.getAllGroupCtr = function() {
    var GroupListTool = [
        GroupFive,
        GroupSameTypeShunZi,
        GroupASameCardType,
        GroupFourAndOneTool,
        GroupThreeAndAPairs,
        GroupSameType,
        GroupShunZi,
        GroupFiveThree,
        GroupTwoPairs,
        GroupFiveAPairs
    ];
    return GroupListTool;
};

IntelligentTool.autoFindOneGroup = function(cardInfoList, needGroupNumber, All) {
    var result = null;
    var GroupListTool = this.getAllGroupCtr();
    var size = _.size(GroupListTool);
    if (null == All) {
        All = [];
    }
    var oneGroupCard = [];
    for (var i = 0; i < size; ++i) {
        if (needGroupNumber == _.size(All)) {
            break;
        }
        oneGroupCard = [];
        /**找到第1组 */
        result = GroupListTool[i].getMoreResult(_.clone(cardInfoList));
        var type1 = GroupListTool[i].getType();
        if (false == result.isFind) {
            oneGroupCard = [];
            continue;
        }
        var singleSizeMax = _.size(result.findGroupMore);
        /**找到第1组的二维处理 */
        for (var j = 0; j < singleSizeMax; ++j) {
            if (needGroupNumber == _.size(All)) {
                break;
            }
            oneGroupCard = [];
            var addGroup = result.findGroupMore[j];

            var oneFristGroup = this.x(addGroup.findGroup, type1);
            oneGroupCard.push(oneFristGroup);
            //---------------------------------黄金分割线------------------------------------
            //剩下的8张牌处理
            var otherCardInfoList = _.difference(_.clone(cardInfoList), addGroup.findGroup);
            if (8 != _.size(otherCardInfoList)) {
                console.error('牌数量不为8，计算有异常');
            }

            var secondAndThreeGroup = _.partition(otherCardInfoList, function(_cardInfo, idx) {
                return idx <= 4;
            });

            oneGroupCard.push(this.getDataStyle(secondAndThreeGroup[0]));
            oneGroupCard.push(this.getDataStyle(secondAndThreeGroup[1]));
            All.push(oneGroupCard);
        }
    }
    return All;
};

IntelligentTool.autoFindTwoGroup = function(cardInfoList, needGroupNumber) {
    var result = null;

    /**五同 */
    // result = GroupFive.getMoreResult(cardInfoList); 

    var GroupListTool = this.getAllGroupCtr();

    var size = _.size(GroupListTool);

    var All = [];
    var oneGroupCard = [];
    for (var i = 0; i < size; ++i) {
        if (needGroupNumber == _.size(All)) {
            break;
        }
        oneGroupCard = [];
        /**找到第1组 */
        result = GroupListTool[i].getMoreResult(_.clone(cardInfoList));
        var type1 = GroupListTool[i].getType();
        if (false == result.isFind) {
            oneGroupCard = [];
            continue;
        }
        var singleSizeMax = _.size(result.findGroupMore);
        /**找到第1组的二维处理 */
        for (var j = 0; j < singleSizeMax; ++j) {
            if (needGroupNumber == _.size(All)) {
                break;
            }
            oneGroupCard = [];
            var addGroup = result.findGroupMore[j];

            var oneFristGroup = this.getDataStyle(addGroup.findGroup, type1);
            oneGroupCard.push(oneFristGroup);
            //---------------------------------黄金分割线------------------------------------
            //剩下的8张牌处理
            var otherCardInfoList = _.difference(_.clone(cardInfoList), addGroup.findGroup);
            if (8 != _.size(otherCardInfoList)) {
                console.error('牌数量不为8，计算有异常');
            }
            /**找到第2组 */
            for (var a = i; a < size; ++a) {
                if (needGroupNumber == _.size(All)) {
                    break;
                }
                var result2 = GroupListTool[a].getMoreResult(_.clone(otherCardInfoList));
                var type2 = GroupListTool[a].getType();
                if (false == result2.isFind) {
                    continue;
                }
                var findGroup2 = result2.findGroupMore;
                /**找到第2组二维处理 */
                for (var b = 0; b < _.size(findGroup2); ++b) {
                    if (needGroupNumber == _.size(All)) {
                        break;
                    }
                    var tmpOneGroupCard = _.clone(oneGroupCard);
                    var scondGroup = findGroup2[b];


                    tmpOneGroupCard.push(this.getDataStyle(scondGroup.findGroup, type2));
                    tmpOneGroupCard.push(this.getDataStyle(scondGroup.otherGroup));
                    /***如果出现两组类型一样的要把大的放前面 */
                    if (tmpOneGroupCard[0].type == tmpOneGroupCard[1].type &&
                        (
                            CardGroupType.SP_FIVE_STRAIGHT_FLUSH == tmpOneGroupCard[1].type ||
                            CardGroupType.SP_FIVE_STRAIGHT_FLUSH_FIRST_A == tmpOneGroupCard[1].type ||
                            CardGroupType.SP_FIVE_MIXED_FLUSH_NO_A == tmpOneGroupCard[1].type ||
                            CardGroupType.SP_FIVE_MIXED_FLUSH_FIRST_A == tmpOneGroupCard[1].type ||
                            CardGroupType.SP_FIVE_FLUSH == tmpOneGroupCard[1].type
                        )
                    ) {
                        var cardsInfo1 = CardTool.workCards(tmpOneGroupCard[0].cardIds);
                        cardsInfo1 = _.sortBy(cardsInfo1, function(_cardInfo) {
                            return -_cardInfo.value;
                        });
                        var cardsInfo2 = CardTool.workCards(tmpOneGroupCard[1].cardIds);
                        cardsInfo2 = _.sortBy(cardsInfo2, function(_cardInfo) {
                            return -_cardInfo.value;
                        });

                        var isNeedChange = false;
                        for (var i = 0; i < 5; ++i) {
                            if (cardsInfo1[i].value < cardsInfo2[i].value) {
                                isNeedChange = true;
                                break;
                            }
                        }
                        if (isNeedChange) {
                            tmpOneGroupCard = _.sortBy(tmpOneGroupCard, function(_card, idx) {
                                if (0 == idx) {
                                    return 1;
                                }
                                if (1 == idx) {
                                    return 0;
                                }
                                return idx;
                            })
                        }


                    }
                    All.push(tmpOneGroupCard);
                }

            }
        }
    }

    // console.error("找出%d组，信息：%s", _.size(All), JSON.stringify(All));  
    return All;
};

IntelligentTool.log = function(_singleGroup, idx) {
    console.error("第%d组,前:%s,中:%s,后:%s", (idx + 1),
            JSON.stringify(_singleGroup[0]),
            JSON.stringify(_singleGroup[1]),
            JSON.stringify(_singleGroup[2])
        )
        // console.error("第%d组,前%s,中%s,后%s", (idx + 1), JSON.stringify(_.map(_singleGroup[0], function(_cardInfo) {
        //     return _cardInfo.value
        // })), JSON.stringify(_.map(_singleGroup[1], function(_cardInfo) {
        //     return _cardInfo.value
        // })), JSON.stringify(_.map(_singleGroup[2], function(_cardInfo) {
        //     return _cardInfo.value
        // })))
};

IntelligentTool.getDataStyle = function(cardsList, type) {
    // var cardIds = _.map(cardsList, function(cardInfo) {
    //     return cardInfo.cardId;
    // });

    if (null == type) {
        type = CardGroupType.SP_SINGLE
    }
    // type = CardGroupType.getTypeName(type);
    // return {
    //     type: type,
    //     typeDescribe: CardGroupType.getTypeName(type),
    //     cardIds: cardsList
    // }



    return {
        type: type,
        // typeDescribe: CardGroupType.getTypeName(type),
        cardIds: _.map(cardsList, function(cardInfo) {
            return cardInfo.cardId;
        })
    }
};